<template>
  <div class="p-2">
    <!-- IOT服务器管理 - 服务器列表 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
        <el-form-item label="服务器名称" prop="serverName">
          <el-input
            v-model="queryParams.serverName"
            placeholder="请输入服务器名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="服务器IP" prop="serverIp">
          <el-input
            v-model="queryParams.serverIp"
            placeholder="请输入服务器IP"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="服务器状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="运行中" value="1" />
            <el-option label="已停止" value="0" />
            <el-option label="异常" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="serverList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="服务器ID" align="center" prop="serverId" width="100" />
        <el-table-column label="服务器名称" align="center" prop="serverName" width="150" show-overflow-tooltip />
        <el-table-column label="服务器IP" align="center" prop="serverIp" width="150" />
        <el-table-column label="端口" align="center" prop="port" width="80" />
        <el-table-column label="服务器类型" align="center" prop="serverType" width="120">
          <template #default="scope">
            <el-tag :type="getServerTypeTag(scope.row.serverType)">{{ scope.row.serverType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="运行状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="CPU使用率" align="center" prop="cpuUsage" width="120">
          <template #default="scope">
            <el-progress :percentage="scope.row.cpuUsage" :color="getProgressColor(scope.row.cpuUsage)" />
          </template>
        </el-table-column>
        <el-table-column label="内存使用率" align="center" prop="memoryUsage" width="120">
          <template #default="scope">
            <el-progress :percentage="scope.row.memoryUsage" :color="getProgressColor(scope.row.memoryUsage)" />
          </template>
        </el-table-column>
        <el-table-column label="最后心跳时间" align="center" prop="lastHeartbeat" width="180" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 服务器表单对话框 -->
    <ServerFormDialog
      v-model:visible="open"
      :title="title"
      :form-data="form"
      @save="handleSubmit"
    />

    <!-- 服务器详情对话框 -->
    <ServerDetailDialog
      v-model:visible="detailOpen"
      :detail-data="detailData"
    />
  </div>
</template>

<script setup name="ServerList" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download, View } from '@element-plus/icons-vue'
import ServerFormDialog from './components/ServerFormDialog.vue'
import ServerDetailDialog from './components/ServerDetailDialog.vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const serverList = ref([])
const title = ref('')
const open = ref(false)
const detailOpen = ref(false)
const detailData = ref({})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  serverName: '',
  serverIp: '',
  status: ''
})

// 表单数据
const form = reactive({
  serverId: undefined,
  serverName: '',
  serverIp: '',
  port: 8080,
  serverType: '',
  description: ''
})

// 模拟数据
const mockData = [
  {
    serverId: 'SRV001',
    serverName: 'IOT核心服务器01',
    serverIp: '192.168.1.100',
    port: 8080,
    serverType: 'IOT核心服务',
    status: '1',
    cpuUsage: 45,
    memoryUsage: 67,
    diskUsage: 32,
    lastHeartbeat: '2024-01-15 14:30:25',
    createTime: '2024-01-01 10:00:00',
    description: 'IOT平台核心业务处理服务器'
  },
  {
    serverId: 'SRV002',
    serverName: '数据处理服务器01',
    serverIp: '192.168.1.101',
    port: 8081,
    serverType: '数据处理服务',
    status: '1',
    cpuUsage: 78,
    memoryUsage: 85,
    diskUsage: 56,
    lastHeartbeat: '2024-01-15 14:30:20',
    createTime: '2024-01-01 10:00:00',
    description: '负责设备数据的实时处理和分析'
  },
  {
    serverId: 'SRV003',
    serverName: '消息队列服务器01',
    serverIp: '192.168.1.102',
    port: 5672,
    serverType: '消息队列服务',
    status: '0',
    cpuUsage: 0,
    memoryUsage: 0,
    diskUsage: 45,
    lastHeartbeat: '2024-01-15 13:45:10',
    createTime: '2024-01-01 10:00:00',
    description: '消息队列服务，处理设备消息传输'
  }
]

// 获取服务器类型标签样式
const getServerTypeTag = (type: string) => {
  switch (type) {
    case 'IOT核心服务': return 'primary'
    case '数据处理服务': return 'success'
    case '消息队列服务': return 'warning'
    case '存储服务': return 'info'
    default: return 'primary'
  }
}

// 获取状态标签样式
const getStatusTag = (status: string) => {
  switch (status) {
    case '1': return 'success'
    case '0': return 'danger'
    case '2': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case '1': return '运行中'
    case '0': return '已停止'
    case '2': return '异常'
    default: return '未知'
  }
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#67C23A'
  if (percentage < 80) return '#E6A23C'
  return '#F56C6C'
}

// 查询服务器列表
const getList = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    let filteredData = [...mockData]
    
    // 应用筛选条件
    if (queryParams.serverName) {
      filteredData = filteredData.filter(item => 
        item.serverName.includes(queryParams.serverName)
      )
    }
    if (queryParams.serverIp) {
      filteredData = filteredData.filter(item => 
        item.serverIp.includes(queryParams.serverIp)
      )
    }
    if (queryParams.status) {
      filteredData = filteredData.filter(item => 
        item.status === queryParams.status
      )
    }
    
    serverList.value = filteredData
    total.value = filteredData.length
    loading.value = false
  }, 500)
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.serverName = ''
  queryParams.serverIp = ''
  queryParams.status = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.serverId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加服务器'
}

// 修改按钮操作
const handleUpdate = (row?: any) => {
  reset()
  const serverId = row?.serverId || ids.value[0]
  const server = mockData.find(item => item.serverId === serverId)
  if (server) {
    Object.assign(form, server)
  }
  open.value = true
  title.value = '修改服务器'
}

// 删除按钮操作
const handleDelete = (row?: any) => {
  const serverIds = row?.serverId ? [row.serverId] : ids.value
  ElMessageBox.confirm('是否确认删除服务器编号为"' + serverIds + '"的数据项？')
    .then(() => {
      ElMessage.success('删除成功')
      getList()
    })
    .catch(() => {})
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

// 查看详情
const handleDetail = (row: any) => {
  detailData.value = { ...row }
  detailOpen.value = true
}

// 处理表单提交
const handleSubmit = (formData: any) => {
  // 表单验证和提交逻辑
  ElMessage.success(title.value.includes('添加') ? '新增成功' : '修改成功')
  open.value = false
  getList()
}

// 表单重置
const reset = () => {
  form.serverId = undefined
  form.serverName = ''
  form.serverIp = ''
  form.port = 8080
  form.serverType = ''
  form.description = ''
}

// 组件挂载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>